<?php

class code_mdl extends Model
{
    public static $jf_table = 'jf_code';
    public static $yhq_table = 'yhq_code';


    public function get_code($type, $tb_uid, $nick){

        if($type == 'jf'){
            $table = self::$jf_table;
        }

        if($type == 'yhq'){
            $table = self::$yhq_table;
        }

        $this->dbh->update($table,
            array(
                'openid' => $tb_uid,
                'nick' => $nick,
                'state' => 1,
                'last_time' => date('Y-m-d H:i:s')
            ),
            'id in (
                select temp.id from (
                    select id
                    from '.$table.' A
                    WHERE state <> 1
                    ORDER BY id
                    LIMIT 0, 1
                ) temp
            )'
        );

        $r = '';
        $sql = 'SELECT *
                FROM '.$table.'
                WHERE openid = "'.$tb_uid.'"
                ORDER BY id DESC'
        ;

        $r = $this->dbh->get_one($sql);

        return $r;

        /*update `yhq_code`
        set state = 1
        WHERE `id` in (
            select temp.id from (
                select `id`
                from `yhq_code` A
                WHERE state <> 1
                ORDER BY id
                LIMIT 0, 1
            ) temp
        )*/
    }


    public function save_code($type, $id, $tb_uid, $nick){

        if($type == 'jf'){
            $table = self::$jf_table;
        }

        if($type == 'yhq'){
            $table = self::$yhq_table;
        }

        $this->dbh->update($table,
            array(
                'openid' => $tb_uid,
                'nick' => $nick,
                'state' => 1,
                'last_time' => date('Y-m-d H:i:s')
            ),
            'id='.$id.''
        );

        $sql = 'SELECT *
					FROM '.$table.'
					WHERE id = '.$id
        ;
        $r = $this->dbh->get_one($sql);

        return $r;
    }


}